package cn.stylefeng.guns.modular.demo.controller;

import cn.hutool.crypto.digest.MD5;
import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.UserExtend;
import cn.stylefeng.guns.dao.service.IUserExtendService;
import cn.stylefeng.guns.modular.demo.controller.domain.TokenVO;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;

@RestController
@Slf4j
@ApiResource(name = "开放接口", resBizType = ResBizTypeEnum.BUSINESS)
public class OpenApiController {
    /**
     * 2小时
     */
    Integer TOKEN_DEFAULT_EXPIRE_TIME = 24 * 60 * 60 * 1000;

    @Resource
    private IUserExtendService userExtendService;

    @GetResource(name = "获取token", path = "/token", requiredLogin = false, requiredPermission = false)
    public ResponseData<TokenVO> token(@RequestParam(value = "clientId", required = true) String clientId, @RequestParam(value = "secret", required = true) String secret) {
        UserExtend userExtend = userExtendService.getOne(Wrappers.<UserExtend>lambdaQuery().eq(UserExtend::getClientId, clientId).eq(UserExtend::getSecret, secret));
        if (Objects.isNull(userExtend)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_CLIENT_ERROR);
        }
        long now = System.currentTimeMillis();
        String accessToken = tokenCompute(clientId, now);
        userExtend.setToken(accessToken);
        long expirationTime = now + TOKEN_DEFAULT_EXPIRE_TIME;
        userExtend.setExpirationTime(expirationTime);
        userExtendService.updateById(userExtend);
        TokenVO tokenVO = new TokenVO();
        tokenVO.setExpirationTime(expirationTime);
        tokenVO.setToken(accessToken);
        tokenVO.setClientId(clientId);
        return new SuccessResponseData<>(tokenVO);
    }








    public static String tokenCompute(String clientId, long now) {
        return MD5.create().digestHex16((clientId + UUID.randomUUID().toString() + now).getBytes(StandardCharsets.UTF_8));
    }
}
